package cn.apestar.common.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.mvel2.PropertyAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.apestar.common.DataContants;
import cn.apestar.common.config.Global;
import cn.apestar.modules.sys.utils.UserUtils;

public class CustomExceptionHandler implements HandlerExceptionResolver {

    protected Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {

        // TODO Auto-generated method stub
        String webUrl = "/" + Global.getConfig("WEB_NAME") + "/a/login";
        if (arg3 != null) {
            Map<String, String> result = new HashMap<String, String>();
            result.put(DataContants.APP_JSON_KEY_RESULT_CODE, Integer.toString(DataContants.APP_RESULT_CODE_YC));
            if (arg3 instanceof BaseException) {
                return new ModelAndView(new RedirectView(webUrl));
            }
            if (arg3 instanceof PropertyAccessException) {
                return new ModelAndView(new RedirectView(webUrl));
            }
            if (arg3 instanceof UnauthenticatedException || arg3 instanceof UnauthorizedException) {
                if (UserUtils.getSubject() != null)
                    UserUtils.getSubject().logout();
                return new ModelAndView(new RedirectView(webUrl));
            } else {
                result.put(DataContants.APP_JSON_KEY_MESSAGE, arg3.getMessage());
                arg3.printStackTrace();
            }
            return new ModelAndView(new RedirectView(webUrl));
        }
        return new ModelAndView();
    }

    /**
     * 客户端返回字符串
     * @param response
     * @param string
     * @return
     */
    protected ModelAndView renderString(HttpServletResponse response, String string, String type) {

        try {
            // int code = response.getStatus();
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            // if(code > 0)
            // response.setStatus(code);
            response.getWriter().print(string);
            return new ModelAndView();
        } catch (IOException e) {
            return new ModelAndView();
        }
    }

}